package com.mazaiting.imqq.ui.activity.contacts;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.listener.ConnectStatusChangeListener;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import com.lqr.adapter.LQRAdapterForRecyclerView;
import com.lqr.adapter.LQRViewHolderForRecyclerView;
import com.lqr.recyclerview.LQRRecyclerView;
import com.mazaiting.imqq.R;
import com.mazaiting.imqq.config.Config;
import com.mazaiting.imqq.model.bean.NewFriend;
import com.mazaiting.imqq.model.bean.UserInfo;
import com.mazaiting.imqq.model.db.manager.NewFriendManager;
import com.mazaiting.imqq.model.message.AgreeAddFriendMessage;
import com.mazaiting.imqq.presenter.user.UserManager;
import com.mazaiting.imqq.ui.activity.SearchUserActivity;
import com.mazaiting.imqq.ui.base.BaseActivity;
import com.mazaiting.imqq.utils.ImageLoaderFactory;
import com.orhanobut.logger.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.greenrobot.eventbus.EventBus;

/**
 * 新朋友界面
 *
 * @author mazaiting
 */
public class NewFriendActivity extends BaseActivity {

  private LQRAdapterForRecyclerView<NewFriend> mAdapter;
  private List<NewFriend> mNewFriends = new ArrayList<>();

  @BindView(R.id.toolbar_include_toolbar) Toolbar mToolbar;
  @BindView(R.id.etContent_new_friend) EditText mEtContent;
  @BindView(R.id.tvNewFriend_new_friend) TextView mTvNewFriend;
  @BindView(R.id.rvNewFriend_new_friend) LQRRecyclerView mRvNewFriend;

  @OnClick(R.id.etContent_new_friend) public void onClick(View view) {
    switch (view.getId()) {
      case R.id.etContent_new_friend:
        newIntent(SearchUserActivity.class, null);
        break;
    }
  }

  @Override protected void initData() {
    initToolbar();
    mNewFriends = NewFriendManager.getInstance(this).getAllNewFriend();
    setAdapter();
    //批量更新未读未认证的消息为已读状态
    NewFriendManager.getInstance(this).updateBatchStatus();
  }

  /**
   * 设置适配器
   */
  private void setAdapter() {
    if (null == mAdapter) {
      mAdapter = new LQRAdapterForRecyclerView<NewFriend>(this, R.layout.item_new_friends_rv,
          mNewFriends) {
        @Override
        public void convert(final LQRViewHolderForRecyclerView helper, final NewFriend item, int position) {
          // 加载头像
          String avatar = item.getAvatar();
          if ("null".equals(avatar)) {
            avatar = null;
          }
          ImageLoaderFactory.getLoader()
              .loadAvatar(((ImageView) helper.getView(R.id.ivHeader_new_friend_item)),
                  avatar, R.mipmap.header);
          // 设置用户名
          helper.setText(R.id.tvName_new_friend_item, item.getName());
          // 设置消息
          helper.setText(R.id.tvMsg_new_friend_item, item.getMsg());
          // 检测状态, 已添加时，显示为已添加
          if (Config.STATUS_VERIFIED== item.getStatus()){
            helper.setViewVisibility(R.id.tvAdded_new_friend_item, View.VISIBLE)
                .setViewVisibility(R.id.btnAck_new_friend_item, View.GONE);
          } else {
            helper.setViewVisibility(R.id.tvAdded_new_friend_item, View.GONE)
                .setViewVisibility(R.id.btnAck_new_friend_item, View.VISIBLE);
          }

          // 接受好友请求
          // 添加到好友表中再发送同意添加好友的消息
          helper.getView(R.id.btnAck_new_friend_item).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
              agreeAdd(item, new SaveListener<BmobIMMessage>() {
                @Override public void done(BmobIMMessage message, BmobException e) {
                  if (e == null){
                    helper.setViewVisibility(R.id.tvAdded_new_friend_item, View.VISIBLE)
                        .setViewVisibility(R.id.btnAck_new_friend_item, View.GONE);
                    EventBus.getDefault().post(new MessageEvent());
                  } else {
                    Toast.makeText(NewFriendActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                  }
                }
              });
            }
          });
        }
      };
      mRvNewFriend.setAdapter(mAdapter);
    } else {
      mAdapter.notifyDataSetChanged();
    }
  }

  /**
   * 同意添加
   * @param item 好友
   * @param listener 监听
   */
  private void agreeAdd(final NewFriend item, final SaveListener<BmobIMMessage> listener) {
    UserInfo userInfo = new UserInfo();
    userInfo.setObjectId(item.getUid());
    UserManager.getInstance().agreeAddFriend(userInfo, new SaveListener<String>() {
      @Override public void done(String s, BmobException e) {
        if (e == null){ // 保存成功
          agreeAddFriend(item, listener);
        } else { // 发送失败
          Logger.e("同意好友请求发送失败");
          listener.done(null, e);
        }
      }
    });
  }

  /**
   * 同意添加好友
   * @param item 新朋友
   * @param listener 发送监听
   */
  private void agreeAddFriend(final NewFriend item, final SaveListener<BmobIMMessage> listener) {
    // 创建一个用户信息
    BmobIMUserInfo info = new BmobIMUserInfo(item.getUid(), item.getName(), item.getAvatar());
    // 创建一个暂态会话入口
    BmobIMConversation conversation =
        BmobIM.getInstance().startPrivateConversation(info, true, null);
    // 根据会话入口获取消息管理， 发送同意好友请求
    BmobIMConversation messageManager = BmobIMConversation.obtain(BmobIMClient.getInstance(), conversation);
    // 获取当前用户
    final UserInfo currentUser = BmobUser.getCurrentUser(UserInfo.class);
    // 而AgreeAddFriendMessage的isTransient设置为false，表明我希望在对方的会话数据库中保存该类型的消息
    final AgreeAddFriendMessage msg = new AgreeAddFriendMessage();
    // 这句话是直接存储到对方的消息表中的
    msg.setContent("我通过了你的好友验证请求，我们可以开始 聊天了!");
    Map<String, Object> map = new HashMap<>();
    // 显示在通知栏上面的内容
    map.put("msg", currentUser.getUsername() + "同意添加你为好友");
    // 发送者的uid-方便请求添加的发送方找到该条添加好友的请求
    map.put("uid", item.getUid());
    // 添加好友的时间
    msg.setExtraMap(map);
    messageManager.sendMessage(msg, new MessageSendListener() {
      @Override public void done(BmobIMMessage bmobIMMessage, BmobException e) {

        if (e == null){// 发送成功
          // 修改本地的好友请求记录
          NewFriendManager.getInstance(NewFriendActivity.this).updateNewFriend(item, Config.STATUS_VERIFIED);
        }
        listener.done(bmobIMMessage, e);
      }
    });

  }

  @Override public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.menu_one_text, menu);
    return super.onCreateOptionsMenu(menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home: // 左上角返回按钮
        finish();
        break;
      case R.id.itemOne:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 初始化Toolbar
   */
  private void initToolbar() {
    setSupportActionBar(mToolbar);
    if (null != getSupportActionBar()) {
      getSupportActionBar().setTitle("新的朋友");
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      mToolbar.setNavigationIcon(R.mipmap.ic_back);
    }
  }

  @Override protected int getLayoutId() {
    return R.layout.activity_new_friend;
  }
}
